package com.bulletelc.apollopre.module.main.cart;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.CartListBean;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.WxShareBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/01/19
 * desc  : TODO
 */

public class CartPresenter extends BasePresenter<CartContract.View> implements CartContract.Presenter {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getCartList(String token) {
        getCartListImp(token);
    }

    @Override
    public void addCount(String json, String token, int groupPosition, int childPosition, boolean isChecked) {
        countChange(json, token, true, groupPosition, childPosition, isChecked);
    }

    @Override
    public void reduceCount(String json, String token, int groupPosition, int childPosition, boolean isChecked) {
        countChange(json, token, false, groupPosition, childPosition, isChecked);
    }

    @Override
    public void deleteCart(String json, String token) {
        deleteCartImp(json, token);
    }

    @Override
    public void clearing(String json, String token) {
        clearingImp(json, token);
    }

    @Override
    public void createCartShare(String cid) {
        createCartShareImp(cid);
    }

    @Override
    public void shareCallback(String cid) {
        shareCallbackImp(cid);
    }

    /**
     * 获取购物车列表
     */
    private void getCartListImp(String token) {
        OkGo.<String>post(NetWorkPath.POST_CART_LIST)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .params("eshop_id", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCartList(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCartList(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解释购物车列表数据
     *
     * @param response
     */
    private void parseCartList(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getName().contains("sub_total");
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create();
                    Type type = new TypeToken<List<CartListBean>>() {
                    }.getType();
                    List<CartListBean> cartListBeans = gson.fromJson(object.getJSONArray("data").toString(), type);
                    if (isViewAttached()) {
                        getView().onSuccessCartList(cartListBeans);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCartList("数据解析错误");
                }
            }

        } else {
            if (isViewAttached()) {
                getView().onFailCartList(response.body().toString());
            }
        }
    }

    /**
     * 增加/减少商品购买数量
     *
     * @param json
     * @param token
     * @param isAdd
     * @param groupPosition
     * @param childPosition
     * @param isChecked
     */
    private void countChange(String json, String token, final boolean isAdd, final int groupPosition, final int childPosition, final boolean isChecked) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CART_UPDATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCountChange(response, isAdd, groupPosition, childPosition, isChecked);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCountChange(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析增加/减少数量返回的数据
     *
     * @param response
     * @param isAdd
     * @param groupPosition
     * @param childPosition
     * @param isChecked
     */
    private void parseCountChange(Response<String> response, boolean isAdd, int groupPosition, int childPosition, boolean isChecked) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    if (isViewAttached()) {
                        getView().onSuccessCountChange(isAdd, groupPosition, childPosition, isChecked);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCountChange(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCountChange("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCountChange(response.body().toString());
            }
        }
    }

    /**
     * 删除购物车产品
     */
    private void deleteCartImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CART_DELETE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseDeleteCart(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorDeleteCart(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析删除购物车商品返回的数据
     *
     * @param response
     */
    private void parseDeleteCart(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    if (isViewAttached()) {
                        getView().onSuccessDeleteCart();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailDeleteCart(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorDeleteCart("解释数据有误");
                }
            }

        } else {
            if (isViewAttached()) {
                getView().onFailDeleteCart(response.body().toString());
            }
        }
    }

    /**
     * 去结算
     *
     * @param json
     * @param token
     */
    private void clearingImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CART_CHECK)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseClearing(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorClearing(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解释去结算返回的数据
     *
     * @param response
     */
    private void parseClearing(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new Gson();
                    OrderConfirmBean confirmBean = gson.fromJson(object.getJSONObject("data").toString(), OrderConfirmBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessClearing(confirmBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailClearing(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorClearing("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailClearing(response.body().toString());
            }
        }
    }

    /**
     * 获取购物车分享内容
     */
    private void createCartShareImp(String cid) {
        String json = "";
        JSONObject object = new JSONObject();
        try {
            object.put("cid", cid);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CREATE_CART_SHARE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, NetWorkPath.AUTH_TOKEN_PRE + MyApplication.getToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCreateCartShare(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorClearing(response.getException().toString());
                        }
                    }
                });
    }

    private void parseCreateCartShare(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    JSONObject data = object.getJSONObject("data");
                    Gson gson = new Gson();
                    Type type = new TypeToken<WxShareBean>() {}.getType();
                    WxShareBean wxShareBean = gson.fromJson(object.getJSONObject("data").toString(), type);
                    if (isViewAttached()) {
                        getView().onSuccessCreateCartShare(wxShareBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCreateCartShare(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCreateCartShare("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCreateCartShare(response.body().toString());
            }
        }
    }

    public void shareCallbackImp(String cid) {
        String json = "";
        JSONObject object = new JSONObject();
        try {
            object.put("id", cid);
            object.put("type", "20");
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody responseBody = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);

        OkGo.<String>post(NetWorkPath.POST_CART_SHARE_SUCCESS)
                .headers(NetWorkPath.HEADER_KEY_AUTH, NetWorkPath.AUTH_TOKEN_PRE + MyApplication.getToken())
                .upRequestBody(responseBody)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parsePostCartShare(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    private void parsePostCartShare(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    if (isViewAttached()) {
                        getView().onSuccessShareCart(object.getBoolean("data"));
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailShareCart(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorShareCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailShareCart(response.body().toString());
            }
        }
    }


}
